<?php
/**
 *
 * User: lang@vip.deyi.com
 * Date: 2017/4/20
 * Time: 15:59
 */

namespace Apps\Common\Service;


use Apps\Common\Constant\CacheKeyConstant;
use Apps\Common\Constant\CacheTimeoutConstant;
use Apps\Common\Constant\ExceptionConstant;
use Deyi\Functions\CacheFunction;

class ReqFreqControlService extends BaseService
{
    public function rateLimitByReids($cacheKeySuffix, $total, $expire = CacheTimeoutConstant::LOCAL_CACHE, $msg = '请求频率过快!', $throw = true)
    {
        $cacheKey = CacheFunction::generateKey(CacheKeyConstant::API_REQ_OVER_LIMIT_CACHE_KEY, $cacheKeySuffix);

        self::$_ns_redis->set($cacheKey, 0, ['nx', 'ex' => $expire]);
        if (self::$_ns_redis->incr($cacheKey) > $total) {
            if ($throw) {
                throw new \Exception($msg, ExceptionConstant::REQ_OVER_LIMIT);
            } else {
                return false;
            }
        }
        return true;
    }

    public function rateLimitByLocalCache($cacheKeySuffix, $total, $expire = CacheTimeoutConstant::LOCAL_CACHE, $msg = '请求频率过快!', $throw = true)
    {
        $cacheKey = CacheFunction::generateKey(CacheKeyConstant::API_REQ_OVER_LIMIT_CACHE_KEY, $cacheKeySuffix);

        apcu_add($cacheKey, 0, $expire);

        if (apcu_inc($cacheKey) > $total) {
            if ($throw) {
                throw new \Exception($msg, ExceptionConstant::REQ_OVER_LIMIT);
            } else {
                return false;
            }
        }

        return true;
    }
}